package com.corecloud.controller.sys;

import com.corecloud.entity.SysSchool;
import com.corecloud.entity.Vocational;
import com.corecloud.service.SysSchoolService;
import com.corecloud.tools.AjaxResultData;
import com.corecloud.tools.ExcelUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/excel")
public class ExcelImportController {

    @Autowired
    private SysSchoolService sysSchoolService;


    @PostMapping("/import")
    public AjaxResultData importExcel(@RequestPart("file") MultipartFile file) {
        if (file.isEmpty()) {
            return new AjaxResultData(300, "文件为空，请按条件录入内容");
        }

        try {
            // 从上传的 Excel 文件中读取数据
            InputStream inputStream = file.getInputStream();
            ExcelUtil.ImportResult importResult = ExcelUtil.readExcel(inputStream);

            List<Vocational> successList = importResult.getSuccessList();
            List<Vocational> failList = importResult.getFailList();

            List<SysSchool> sysSchools = new ArrayList<>();
            successList.forEach(item -> {
                SysSchool sysSchool = new SysSchool();
                BeanUtils.copyProperties(item, sysSchool);
                sysSchools.add(sysSchool);
            });
            // 使用Stream API进行去重
            List<SysSchool> distinctSchools = sysSchools.stream()
                    .collect(Collectors.toMap(SysSchool::getSchoolName, sysSchool -> sysSchool, (existing, replacement) -> existing))
                    .values()
                    .stream()
                    .collect(Collectors.toList());
            // 调用 Service 层进行批量插入
            sysSchoolService.saveBatch(distinctSchools);

            // 返回导入结果给前端
            Map<String, Object> data = new HashMap<>();
            data.put("successList", successList.size());
            data.put("failList", failList.size());
            return new AjaxResultData(200, "导入成功", data);
        } catch (IOException e) {
            return new AjaxResultData(500, "导入失败");
        }
    }
//            sysSchoolService.batchSave(sysSchools);
    /**
     * 下载模板文件
     * @param type 1 为高职 2为中职
     * @return
     * @throws IOException
     */
    @GetMapping("/download/template/{type}")
    public ResponseEntity<Resource> downloadTemplate(@PathVariable("type") Integer type) throws IOException {
        String filePath = null;
        String fileName = null;

        if (1 == type) {
            filePath = "E:/test/中职学校导入模板.xlsx";
            fileName = "中职学校导入模板.xlsx";
        } else {
            filePath = "E:/test/高职学校导入模板.xlsx";
            fileName = "高职学校导入模板.xlsx";
        }

        Path path = Paths.get(filePath);

        // 读取文件资源
        Resource resource = new UrlResource(path.toUri());

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);

        // 返回文件响应
        return ResponseEntity.ok()
                .headers(headers)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
    }
}
